package appModel;

import globalTools.FoldersPaths;
import globalTools.Savable;
import gridModel.PlayableGridModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class StdSaveData extends Savable implements SaveData, Serializable, FoldersPaths {

	// ATTRIBUTS
	
	private static final long serialVersionUID = 1L;
	
	private ScoreSheet scoreSheet;
	private PlayableGridModel saved;
	
	// CONSTRUCTEUR
	
	private StdSaveData(ScoreSheet scores) {
		super(SCORES_FILENAME);
		scoreSheet = scores;
		saved = null;
	}
	
	// REQUETES
	
	/* TEMPORAIRE */
	private void corrigeScoreSheet() {
		((StdScoreSheet) scoreSheet).corrigeScore();
	}
	
	public static SaveData getSavedData() throws IOException {
		StdSaveData d = null;
		if (!(new File(SCORES_FILENAME)).exists()) {
			File score  = new File("colorcross.sav");
			if (score.exists()) {
				// Lecture de l'ancienne sauvegarde
				ScoreSheet s = null;
				FileInputStream fis;
				try {
					fis = new FileInputStream(score);
					ObjectInputStream ois = new ObjectInputStream(fis);
					s = (ScoreSheet) ois.readObject();
					ois.close();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				d = new StdSaveData(s);
			} else {
				d = new StdSaveData(new StdScoreSheet());
			}
			d.corrigeScoreSheet();
			d.save();
			score.delete();
		} else {
			d = (StdSaveData) Savable.getSaved(SCORES_FILENAME);
		}
		return d;
	}

	@Override
	public Long getScore(String f) {
		return scoreSheet.getScore(f);
	}

	@Override
	public PlayableGridModel getSavedPlay() {
		return saved;
	}
	
	// COMMANDES

	@Override
	public void saveScore(long t, String s) throws IOException {
		scoreSheet.putScore(t, s);
		save();
	}

	@Override
	public void saveGame(PlayableGridModel play) throws IOException {
		saved = play;
		save();
	}

}
